<template>
  <el-dialog v-loading="loading" class="add-category" :visible="dialogShow" center top="0" :title="addOrEdit === 'add' ? '新增' : '修改'" @close="btnClose">
    <div class="center">
      <el-form ref="form" label-width="80px" :model="formData" :rules="formRules">
        <el-form-item label="相册名称" prop="categoryName">
          <el-input
            v-model="formData.categoryName"
            size="small"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sortNum" size="small" :min="50" :max="1000" @change="changeSortNum" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="btnOk()">确定</el-button>
        <el-button size="small" @click="btnClose()">取消</el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script>
import { addCategory, editCategory } from '@/api/image'
export default {
  name: 'AddCategory',
  props: {
    addOrEdit: {
      type: [String, Object],
      default: 'add'
    },
    dialogShow: {
      type: Boolean,
      default: false
    }

  },
  data() {
    return {
      loading: false,
      formData: {
        id: '',
        categoryName: '',
        sortNum: 1
      },
      formRules: {
        categoryName: [
          { required: true, trigger: 'blur', message: '相册名不能为空' }
        ]
      }
    }
  },
  created() {
    if (this.addOrEdit !== 'add') {
      // 编辑则修改formData数据
      this.formData = {
        id: this.addOrEdit.id,
        categoryName: this.addOrEdit.name,
        sortNum: this.addOrEdit.order
      }
    }
  },
  methods: {
    btnClose() {
      this.$emit('update:dialogShow', false)
      this.$emit('update:addOrEdit', null)
      this.formData = {
        categoryName: '',
        sortNum: 1
      }
      this.$refs.form.resetFields()
    },
    btnOk() {
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          if (this.addOrEdit === 'add') {
            // 新增
            try {
              await addCategory(this.formData.categoryName, this.formData.sortNum)
              this.$emit('getCategoryList')
              this.$message.success('添加相册分类成功')
            } catch (error) {
              console.log(error)
              this.$message.error('添加相册分类失败')
            }
          } else {
            // 编辑
            try {
              await editCategory(this.formData.id, this.formData.categoryName, this.formData.sortNum)
              this.$emit('getCategoryList')
              this.$message.success('修改相册分类成功')
            } catch (error) {
              console.log(error)
              this.$message.error('修改相册分类失败')
            }
          }
          this.btnClose()
        }
      })
    },
    // 添加分类的排序位置
    changeSortNum(num) {
      // console.log(num)
    }
  }
}
</script>

<style lang="scss" scoped>
.add-category {

}
</style>
